package com.csxy.yhj.service.impl;

import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csxy.yhj.entity.CareDescription;
import com.csxy.yhj.entity.CareSe;
import com.csxy.yhj.entity.vo.*;
import com.csxy.yhj.exception.MyException;
import com.csxy.yhj.mapper.CareSEMapper;
import com.csxy.yhj.service.CareSeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class CareSeServiceImpl extends ServiceImpl<CareSEMapper, CareSe> implements CareSeService {


    @Autowired  // 注入服务描述服务
    private CareDescriptionServiceImpl careDescriptionService;

    //想服务表里添加服务基本信息的方法
    //CareInfoForm对象，装换成CareSE对象

    @Override
    public String addCareInfo(CareInfoForm careInfoForm) {
        CareSe carSe = new CareSe();
        BeanUtils.copyProperties(careInfoForm, carSe);
        int result = baseMapper.insert(carSe);

        //获取添加之后服务id
        String cid = carSe.getId();
        CareDescription careDescription = new CareDescription();
        careDescription.setDescription(careInfoForm.getDescription());
        //手动设置描述服务表的id，与上面的服务信息id关联
        careDescription.setId(cid);

        return cid;
    }


    //获取服务信息
    @Override
    public CareInfoForm getCareInfo(String courseId) {
        CareInfoForm courseInfoForm = new CareInfoForm();
        // 查询服务基本信息
        CareSe careSe = baseMapper.selectById(courseId);
        if (careSe == null) {
            // 可选：如果服务本身不存在，可抛出异常或返回空对象
            throw new MyException(20001, "服务不存在");
        }
        BeanUtils.copyProperties(careSe, courseInfoForm);

        // 查询服务描述（添加非空判断）
        CareDescription courseDescription = careDescriptionService.getById(courseId);
        // 如果描述不存在，使用空字符串作为默认值
        String description = (courseDescription != null) ? courseDescription.getDescription() : "";
        courseInfoForm.setDescription(description);

        return courseInfoForm;
    }

    //修改服务信息
    @Override
    public void updateCareInfo(CareInfoForm careInfoForm) {
        //1.修改服务表
        CareSe careSe = new CareSe();
        BeanUtils.copyProperties(careInfoForm, careSe);
        baseMapper.updateById(careSe);
        //2.修改描述信息
        CareDescription eduCourseDescription = new CareDescription();
        eduCourseDescription.setDescription(careInfoForm.getDescription());
        eduCourseDescription.setId(careInfoForm.getId());
        careDescriptionService.updateById(eduCourseDescription);
    }



    //删除服务
    @Override
    public boolean removeCare(String id) {

        //3.根据服务id删除服务描述
        careDescriptionService.removeById(id);
        //4.根据服务id删除服务本身
        int result = baseMapper.deleteById(id);
        if (result >= 1) {
            return true;
        } else {
            throw new MyException(20001, "删除服务失败！");
        }
    }

    //条件查询带分页
    @Override
    public void pageQuery(Page<CareSe> pageParam, CareQuery courseQuery) {
        QueryWrapper<CareSe> queryWrapper = new QueryWrapper<>();

        // 使用安全空值检查
        if (courseQuery != null) {
            if (StringUtils.hasText(courseQuery.getTitle())) {
                queryWrapper.like("title", courseQuery.getTitle());
            }
            if (StringUtils.hasText(courseQuery.getStatus())) {
                queryWrapper.eq("status", courseQuery.getStatus());
            }
        }

        queryWrapper.orderByDesc("gmt_create");
        baseMapper.selectPage(pageParam, queryWrapper);
    }

    // 查询服务信息
    @Autowired
    private CareSEMapper careSEMapper;

    @Override

    public CarePublishVo getPublishCareInfo(String id) {
        return careSEMapper.getPublishCareInfo(id);
    }

    // 查询服务信息[订单]
    @Override
    public CareWebVo getBaseCareInfo(String courseId) {
        return baseMapper.getBaseCourseInfo(courseId);
    }



    // 查询热门服务,浏览量降序，取前8条
    @Override
//    @Cacheable(key = "'selectHotCourse'",value = "course")
    public List<CareSe> selectHotCare() {
        // 查询前8最热门的服务
        QueryWrapper<CareSe> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("view_count");
        wrapper.last("limit 8");

        return baseMapper.selectList(wrapper);
    }

    @Override
    public Map<String, Object> getCareFrontInfo(Page<CareSe> pageCourse, CareFrontVo courseFrontVo) {
        QueryWrapper<CareSe> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(courseFrontVo.getSubjectParentId())){
            wrapper.eq("subject_parent_id",courseFrontVo.getSubjectParentId());
        }
        if (StringUtils.isNotEmpty(courseFrontVo.getSubjectId())){
            wrapper.eq("subject_id",courseFrontVo.getSubjectId());
        }
        if (StringUtils.isNotEmpty(courseFrontVo.getBuyCountSort())){
            wrapper.orderByDesc("buy_count");
        }
        if (StringUtils.isNotEmpty(courseFrontVo.getPriceSort())){
            wrapper.orderByDesc("price");
        }
        if (StringUtils.isNotEmpty(courseFrontVo.getGmtCreateSort())){
            wrapper.orderByDesc("gmt_create");
        }
        careSEMapper.selectPage(pageCourse,wrapper);
        Map<String, Object> map = new HashMap<>();
        long total = pageCourse.getTotal();
        List<CareSe> courseList = pageCourse.getRecords();
        long size = pageCourse.getSize();
        long current = pageCourse.getCurrent();
        long pages = pageCourse.getPages();
        boolean hasPrevious = pageCourse.hasPrevious();
        boolean hasNext = pageCourse.hasNext();
        map.put("total",total);
        map.put("list",courseList);
        map.put("size",size);
        map.put("current",current);
        map.put("pages",pages);
        map.put("hasPrevious",hasPrevious);
        map.put("hasNext",hasNext);
        return map;

    }
}
